package algorithm_demo.demo01;

import java.util.ArrayList;
import java.util.List;

/**
 * https://leetcode.cn/problems/path-sum-ii/
 * <p>
 * 给你二叉树的根节点 root 和一个整数目标和 targetSum ，找出所有 从根节点到叶子节点 路径总和等于给定目标和的路径。
 * <p>
 * 叶子节点 是指没有子节点的节点。
 * <p>
 * 来源：力扣（LeetCode）
 * 链接：https://leetcode.cn/problems/path-sum-ii
 * 著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。
 *
 * @author Api
 * @date 2023/2/5 16:46
 */
public class Code34_PathSumII {
    public static class TreeNode {
        public int val;
        public TreeNode left;
        public TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public static List<List<Integer>> pathSum(TreeNode root, int targetSum) {
        List<List<Integer>> ans = new ArrayList<>();
        if (root == null) {
            return ans;
        }
        List<Integer> path = new ArrayList<>();
        process(root, path, 0, targetSum, ans);
        return ans;
    }

    public static void process(TreeNode x, List<Integer> path, int preSum, int targetSum, List<List<Integer>> ans) {
        if (x.left == null && x.right == null) {
            if (preSum + x.val == targetSum) {
                path.add(x.val);
                ans.add(copy(path));
                path.remove(path.size() - 1);
            }
        }

        //x是非叶子节点
        path.add(x.val);

        preSum += x.val;
        if (x.left != null) {
            process(x.left, path, preSum, targetSum, ans);
        }
        if (x.right != null) {
            process(x.right, path, preSum, targetSum, ans);
        }
        path.remove(path.size() - 1);
    }


    public static List<Integer> copy(List<Integer> path) {
        return new ArrayList<>(path);
    }

    public static void main(String[] args) {
        TreeNode root = new TreeNode(5);
        root.left = new TreeNode(4);
        root.right = new TreeNode(8);
        root.left.left = new TreeNode(11);
        root.left.right = null;
        root.right.left = new TreeNode(13);
        root.right.right = new TreeNode(4);
        root.left.left.left = new TreeNode(7);
        root.left.left.right = new TreeNode(2);
        root.right.right.left = new TreeNode(5);
        root.right.right.right = new TreeNode(1);
        List<List<Integer>> lists = pathSum(root, 22);
        System.out.println(lists);
    }
}
